#include "headers/mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QTableWidgetItem>
#include <QString>
#include <QDesktopServices>
#include <QUrl>
#include "headers/markedprocessmanagerdialog.h"
#include "headers/LoginDialog.h"
#include "headers/AuthClient.h"
#include "headers/EmailSender.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_authClient(new AuthClient(this)),
    m_emailSender(new EmailSender(this))
{
    ui->setupUi(this);
    processMonitor = new ProcessMonitor(this);
    screenCapture = new ScreenCapture(this);
    markedGameManager = new MarkedGameManager(this);

    // 加载已标记的游戏进程
    QStringList markedGames = markedGameManager->loadMarkedGames();
    if (!markedGames.isEmpty()) {
        processMonitor->setGameProcessNames(markedGames);
        ui->markStatusLabel->setText(QString("已加载 %1 个标记游戏进程").arg(markedGames.size()));
    } else {
        ui->markStatusLabel->setText("暂无标记的游戏进程，可手动标记");
    }

    // 核心信号槽连接
    connect(processMonitor, &ProcessMonitor::gameProcessDetected,
            screenCapture, &ScreenCapture::captureScreen);
    connect(screenCapture, &ScreenCapture::captureFinished,
            this, &MainWindow::onCaptureFinished);
    connect(processMonitor, &ProcessMonitor::allProcessUpdated,
            this, &MainWindow::onAllProcessUpdated);
    connect(processMonitor, &ProcessMonitor::allProcessUpdated,
            this, &MainWindow::refreshProcessSelectionCombo);
    connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::onStartMonitorClicked);
    connect(ui->pushButton_2, &QPushButton::clicked, this, &MainWindow::onStopMonitorClicked);
    connect(ui->markAsGameBtn, &QPushButton::clicked, this, &MainWindow::onMarkAsGameBtnClicked);

    connect(ui->openManagerBtn, &QPushButton::clicked, this, [this]() {
        MarkedProcessManagerDialog *dialog = new MarkedProcessManagerDialog(markedGameManager, this);
        dialog->setAttribute(Qt::WA_DeleteOnClose);
        connect(dialog, &MarkedProcessManagerDialog::markedProcessUpdated, this, [this]() {
            QStringList updatedGames = markedGameManager->loadMarkedGames();
            processMonitor->setGameProcessNames(updatedGames);
            ui->markStatusLabel->setText(QString("已加载 %1 个标记游戏进程").arg(updatedGames.size()));
        });
        dialog->exec();
    });

    // 触发登录流程
    connect(ui->loginBtn, &QPushButton::clicked, this, [this]() {
        LoginDialog loginDialog(m_authClient, m_emailSender, this);
        if (loginDialog.exec() == QDialog::Accepted && loginDialog.isLoginSuccess()) {
            ui->loginBtn->hide();
        }
    });

    ui->allProcessTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 开始监控按钮逻辑
void MainWindow::onStartMonitorClicked()
{
    processMonitor->startMonitor(2000);
    ui->label->setText("监控状态：运行中");
    ui->label->setStyleSheet("color: green;");
}

// 停止监控按钮逻辑
void MainWindow::onStopMonitorClicked()
{
    processMonitor->stopMonitor();
    ui->label->setText("监控状态：已停止");
    ui->label->setStyleSheet("color: red;");
}

// 截屏完成后，更新违规记录表格
void MainWindow::onCaptureFinished(const QString &screenshotPath)
{
    QString processName = screenshotPath.section('_', 2, 2).section('.', 0, 0);
    QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

    int newRow = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(newRow);

    QTableWidgetItem *timeItem = new QTableWidgetItem(currentTime);
    timeItem->setFlags(timeItem->flags() & ~Qt::ItemIsEditable);
    ui->tableWidget->setItem(newRow, 0, timeItem);

    QTableWidgetItem *nameItem = new QTableWidgetItem(processName);
    nameItem->setFlags(nameItem->flags() & ~Qt::ItemIsEditable);
    ui->tableWidget->setItem(newRow, 1, nameItem);

    QTableWidgetItem *pathItem = new QTableWidgetItem(screenshotPath);
    pathItem->setFlags(pathItem->flags() & ~Qt::ItemIsEditable);
    ui->tableWidget->setItem(newRow, 2, pathItem);
}

// 刷新所有进程列表
void MainWindow::onAllProcessUpdated(const QList<ProcessInfo> &processList)
{

    ui->allProcessTable->setRowCount(0);

    for (int i = 0; i < processList.size(); ++i) {
        const ProcessInfo &info = processList[i];
        ui->allProcessTable->insertRow(i);

        QTableWidgetItem *nameItem = new QTableWidgetItem(info.processName);
        nameItem->setFlags(nameItem->flags() & ~Qt::ItemIsEditable);
        ui->allProcessTable->setItem(i, 0, nameItem);

        QString cpuText = QString::number(info.cpuUsage, 'f', 1) + "%";
        QTableWidgetItem *cpuItem = new QTableWidgetItem(cpuText);
        cpuItem->setFlags(cpuItem->flags() & ~Qt::ItemIsEditable);
        cpuItem->setTextAlignment(Qt::AlignRight);
        ui->allProcessTable->setItem(i, 1, cpuItem);
    }
}

// 刷新进程选择下拉框
void MainWindow::refreshProcessSelectionCombo(const QList<ProcessInfo> &processList)
{
    QString lastSelectedText = ui->processSelectionCombo->currentText();

    ui->processSelectionCombo->clear();
    QStringList uniqueNames;
    for (const auto &info : processList) {
        if (!uniqueNames.contains(info.processName)) {
            uniqueNames.append(info.processName);
        }
    }
    ui->processSelectionCombo->addItems(uniqueNames);

    if (!lastSelectedText.isEmpty() && uniqueNames.contains(lastSelectedText)) {
        int targetIndex = ui->processSelectionCombo->findText(lastSelectedText);
        ui->processSelectionCombo->setCurrentIndex(targetIndex);
    }
}

// 标记选中/输入的进程为游戏
void MainWindow::onMarkAsGameBtnClicked()
{
    QString processName = ui->processInputEdit->text().trimmed();
    if (processName.isEmpty()) {
        processName = ui->processSelectionCombo->currentText();
    }

    if (processName.isEmpty()) {
        ui->markStatusLabel->setText("请在输入框输入进程名，或从下拉框选择！");
        ui->markStatusLabel->setStyleSheet("color: orange;");
        return;
    }

    bool success = markedGameManager->addMarkedGame(processName);
    if (success) {
        QStringList updatedGames = markedGameManager->loadMarkedGames();
        processMonitor->setGameProcessNames(updatedGames);
        ui->markStatusLabel->setText(QString("✅ 成功标记「%1」为游戏进程").arg(processName));
        ui->markStatusLabel->setStyleSheet("color: green;");
        ui->processInputEdit->clear();
    } else {
        ui->markStatusLabel->setText(QString("❌ 「%1」已被标记为游戏进程，无需重复操作").arg(processName));
        ui->markStatusLabel->setStyleSheet("color: red;");
    }
}
